package com.atguigu.gulimall.seckill.service.impl;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.atguigu.entity.to.SeckillOrderTO;
import com.atguigu.entity.vo.MemberResponseVo;
import com.atguigu.gulimall.seckill.entity.to.SeckillSkuRedisTo;
import com.atguigu.gulimall.seckill.entity.vo.SeckillSessionWithSkusVo;
import com.atguigu.gulimall.seckill.entity.vo.SkuInfoVo;
import com.atguigu.gulimall.seckill.feign.CouponFeignService;
import com.atguigu.gulimall.seckill.feign.ProductFeignService;
import com.atguigu.gulimall.seckill.interceptor.LoginUserInterceptor;
import com.atguigu.gulimall.seckill.service.SeckillService;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    RedissonClient redissonClient;

    private final String SESSION_CACHE_PREFIX = "seckill:session:";

    private final String SKUKILL_CACHE_PREFIX = "seckill:skus:";

    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:";//+商品随机码

    @Override
    public void uploadSeckillSkuLatest3Days() {
        //1.扫码需要参与秒杀的活动
        R r = couponFeignService.getLatest3DaysSession();
        if (r.getCode() == 0){
            //上架商品
            List<SeckillSessionWithSkusVo> data = r.getData(new TypeReference<List<SeckillSessionWithSkusVo>>() {
            });
            //缓存到redis
            //1。缓存活动信息
            saveSessionInfos(data);

            //2。缓存活动关联到商品
            saveSessionSkuInfos(data);

        }
    }

    /**
     * blockHandler会在原方法被限流/降级/系统保护是被调用
     * 而 fallback 会在针对所有类型的异常是被调用
     * @return
     */
    @SentinelResource(value = "getCurrentSeckillSkusResource",blockHandler = "blockHandler",fallback = "fallback")
    @Override
    public List<SeckillSkuRedisTo> getCurrentSeckillSkus() {
        //确定当前时间属于那个秒杀场次
        long time = new Date().getTime();

        //自定义保护的资源
        //自定义限流，控制台有currentSeckillSkus限流的配置
        try(Entry entry = SphU.entry("currentSeckillSkus")){
            //1获取seckill:session:开头所有的key
            Set<String> keys = redisTemplate.keys(SESSION_CACHE_PREFIX + "*");
            for (String key : keys) {
                //seckill:session:1626134400000_1626220799000
                String replace = key.replace("seckill:session:", "");
                String[] s = replace.split("_");
                Long start = Long.parseLong(s[0]);
                Long end = Long.parseLong(s[1]);

                if (time >= start && time <= end){
                    //2.获取这个秒杀场次需要的所有商品信息
                    List<String> range = redisTemplate.opsForList().range(key, -100, 100);
                    BoundHashOperations<String,String,String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                    List<String> list = hashOps.multiGet(range);
                    if (list != null){
                        List<SeckillSkuRedisTo> collect = list.stream().map(item -> {
                            SeckillSkuRedisTo redisTo = JSON.parseObject((String) item, SeckillSkuRedisTo.class);
                            //不需要把随机码给到客户端，当前秒杀开始了需要随机码
//                        redisTo.setRandomCode(null);
                            return redisTo;
                        }).collect(Collectors.toList());

                        return collect;
                    }
                    break;
                }
            }
        } catch (BlockException e) {
            log.info("限流后处理.....");
            e.printStackTrace();
        }


        return null;
    }

    public List<SeckillSkuRedisTo> blockHandler(BlockException e){
        log.error("getCurrentSeckillSkus被限流了");
        return null;
    }

    @Override
    public SeckillSkuRedisTo getSkuSeckillInfo(Long skuId) {
        //找到所有需要参与秒杀的商品key
        BoundHashOperations<String,String,String> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        Set<String> keys = ops.keys();
        if (keys != null && keys.size() > 0){
            String regx = "\\d_"+skuId;
            for (String key : keys) {
                boolean matches = Pattern.matches(regx, key);
                if (matches){
                    String json = ops.get(key);
                    SeckillSkuRedisTo redisTo = JSON.parseObject(json, SeckillSkuRedisTo.class);
                    //随机码处理，预告是不能返回随机码
                    Long startTime = redisTo.getStartTime();
                    Long endTime = redisTo.getEndTime();
                    long time = new Date().getTime();
                    if (time >= startTime && time <= endTime){
                    }else {
                        redisTo.setRandomCode(null);
                    }

                    return redisTo;
                }
            }
        }
        return null;
    }

    @Override
    public String kill(String killId, String key, Integer num) {
        //1。登录校验 拦截器处理
        MemberResponseVo responseVo = LoginUserInterceptor.loginUser.get();
        //2.获取当前秒杀商品的合法性
        BoundHashOperations<String,String,String> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        String s = ops.get(killId);
        if (StringUtils.isEmpty(s)){
            return null;
        }

        SeckillSkuRedisTo redisTo = JSON.parseObject(s, SeckillSkuRedisTo.class);
        //校验时间的合法性
        Long startTime = redisTo.getStartTime();
        Long endTime = redisTo.getEndTime();
        long time = new Date().getTime();
        if (time <= startTime || time >= endTime){
            return null;
        }

        //校验随机码和商品id是否正确
        String randomCode = redisTo.getRandomCode();
        String skuId = redisTo.getPromotionSessionId() + "_" + redisTo.getSkuId();
        if (!randomCode.equals(key) || !killId.equals(skuId)){
            return null;
        }

        //校验购物数量是否合理
        BigDecimal seckillLimit = redisTo.getSeckillLimit();
        if (seckillLimit.compareTo(new BigDecimal(num.toString())) == -1){
            return null;
        }

        //校验这个用户是否已经购买过。幂等性处理，如果只要秒杀成功，就去占位。userId_SessionId_skuId
        String redisKey = responseVo.getId()+"_"+skuId;
        //设置自动过期
        Long ttl = endTime - time;
        //setIfAbsent 如果redis中存在这个key 会是指失败 redis中的SETNX命令
        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MILLISECONDS);//值随便
        //如果占位成功说明这个用户没有买过，如果占位失败，说明这个用户买过
        if (!aBoolean){
            return null;
        }

        //获取信号量
        RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
//        try {
//            semaphore.acquire(num);//这个方法是阻塞的
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        try {
            //用100毫秒快速尝试，
            //指定的时间内尝试地获得1个许可，如果获取不到则返回false
            boolean b = semaphore.tryAcquire(num, 100, TimeUnit.MILLISECONDS);
            if (!b){
                return null;
            }
            //秒杀成功，发MQ消息 10ms
            String orderSn = IdWorker.getTimeId();
            SeckillOrderTO seckillOrderTO = new SeckillOrderTO();
            seckillOrderTO.setOrderSn(orderSn);
            seckillOrderTO.setPromotionSessionId(redisTo.getPromotionSessionId());
            seckillOrderTO.setNum(num);
            seckillOrderTO.setSeckillPrice(redisTo.getSeckillPrice());
            seckillOrderTO.setSkuId(redisTo.getSkuId());
            seckillOrderTO.setMemberId(responseVo.getId());

            rabbitTemplate.convertAndSend("order-event-exchange","order.seckill.order",seckillOrderTO);

            return orderSn;
        } catch (InterruptedException e) {
            e.printStackTrace();

            return null;
        }
    }

    private void saveSessionInfos(List<SeckillSessionWithSkusVo> sessions){
        if (sessions == null || sessions.size() == 0){
            return;
        }
        sessions.stream().forEach(session -> {
            Long startTime = session.getStartTime().getTime();
            Long endTime = session.getEndTime().getTime();
            List<String> skuIds = session.getRelationSkus().stream().map(item->item.getId()+"_"+item.getSkuId()).collect(Collectors.toList());

            String key = SESSION_CACHE_PREFIX + startTime+"_"+endTime;
            //缓存活动信息
            if (skuIds!= null && skuIds.size()>0){

                Boolean hasKey = redisTemplate.hasKey(key);
                if (!hasKey){
                    redisTemplate.setKeySerializer(RedisSerializer.string());
                    redisTemplate.setHashKeySerializer(RedisSerializer.string());
                    redisTemplate.setValueSerializer(RedisSerializer.json());
                    redisTemplate.opsForList().leftPushAll(key,skuIds);
                }
            }
        });
    }

    private void saveSessionSkuInfos(List<SeckillSessionWithSkusVo> sessions){

        if (sessions == null || sessions.size() == 0){
            return;
        }
        sessions.stream().forEach(session->{
            //准备hash操作
            BoundHashOperations<String,Object,Object> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
            session.getRelationSkus().stream().forEach(skuVo -> {

                String token = UUID.randomUUID().toString().replace("-", "");

                if (!ops.hasKey(skuVo.getPromotionSessionId() + "_" + skuVo.getSkuId())){
                    //缓存商品
                    SeckillSkuRedisTo to = new SeckillSkuRedisTo();
                    //1.sku的基本信息
                    R info = productFeignService.getSkuinfo(skuVo.getSkuId());
                    if (info.getCode() == 0){
                        SkuInfoVo skuInfo = info.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                        });
                        to.setSkuInfoVo(skuInfo);
                    }

                    //2。sku的秒杀信息
                    BeanUtils.copyProperties(skuVo,to);

                    //3。当前商品秒杀的时间信息
                    to.setStartTime(session.getStartTime().getTime());
                    to.setEndTime(session.getEndTime().getTime());

                    //4.商品的随机码？ 防止写脚本来刷，随机码只有活动开始来才有
                    to.setRandomCode(token);

                    ops.put(skuVo.getPromotionSessionId() + "_" + skuVo.getSkuId(), JSON.toJSONString(to));

                    //如果当前这个场次的商品的库存信息已经上架就不需要上架
                    //引入分布式的型号量
                    //获取一个信号量  作用：限流
                    RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + token);
                    //将商品可以秒杀的数量作为信号量
                    semaphore.trySetPermits(skuVo.getSeckillCount().intValue());
                }
            });
        });
    }
}
